package com.gary.spring.webContainer.A01;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author peng_rui
 * @date 2022/7/10
 */
@Configuration
@ComponentScan
@PropertySource("classpath:application.properties")
// 获取指定配置文件 指定前缀的配置信息
@EnableConfigurationProperties({WebMvcProperties.class, ServerProperties.class})
public class MyWebConfig {
    /**
     * 1. 创建web容器
     * @return
     */
    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        return new TomcatServletWebServerFactory();
    }
    /**
     * 2. 创建DispatchServlet容器
     */
    @Bean
    public DispatcherServlet dispatcherServlet() {
        return  new DispatcherServlet();
    }

    /**
     * 3. 将dispatchServlet注册到web容器中
     * @param dispatcherServlet
     * @return
     */
    @Bean
    public DispatcherServletRegistrationBean dispatcherServletRegistrationBean(
            DispatcherServlet dispatcherServlet, WebMvcProperties webMvcProperties) {
        DispatcherServletRegistrationBean registrationBean = new DispatcherServletRegistrationBean(dispatcherServlet, "/");
        int loadOnStartup = webMvcProperties.getServlet().getLoadOnStartup();
        registrationBean.setLoadOnStartup(loadOnStartup);
        return registrationBean;
    }

    /**
     * 若使用DispatcherServlet默认的初始化组件，并不会作为bean 注册到容器中
     *             这里进行手动注入容器
     */
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        return new RequestMappingHandlerMapping();
    }

    /**
     * 注入 处理器适配器 作用 调用对应的方法
     * @return
     */
    @Bean
    public MyRequestMappingHandlerAdapter requestMappingHandlerAdapter() {
        MyRequestMappingHandlerAdapter handlerAdapter = new MyRequestMappingHandlerAdapter();
        MyTokenResolve myTokenResolve = new MyTokenResolve();
        YamlResponseHandler yamlResponseHandler = new YamlResponseHandler();
        handlerAdapter.setCustomArgumentResolvers(Arrays.asList(myTokenResolve));
        handlerAdapter.setCustomReturnValueHandlers(Arrays.asList(yamlResponseHandler));
        return handlerAdapter;
    }

}
